import React from 'react';
import { Table, Button, Select, Input, Slider, Form, Modal, Icon } from 'antd';
import { connect } from 'dva';
import styles from './index.less';
import filterData from './filterData';
import moment from 'moment';
import { userId } from '@/constant';
import Achievement from './Achievement';
import beachSrc from '@/assets/images/beach.png';
import Global from '@/components/Global';
const { Option } = Select;
const dateFormat = 'YYYY-MM-DD';
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1235632_sr5cqwo7jfj.js',
});
const { Search } = Input;
const creator = (type, payload) => ({ type, payload });
class Plan extends React.Component {
  constructor(props) {
    super(props);
    // this.myRef = React.createRef();
    this.state = {
      selectedRows: [],
      selectedRowKeys: [], // Check here to configure the default column
      achievementModal: false,
      value: '其他',
      visible: false,
      time: 0,
      complexity: 0,
      record: {},
    };
  }
  componentDidMount() {
    const { dispatch } = this.props;
    const id = window.sessionStorage.getItem(userId);
    let sDate = moment('0000-01-01');
    let eDate = moment('9999-12-31');
    dispatch(creator('plan/getToDoList', { id, sDate, eDate })).then(res => {
      // 批量修改todo类型
      // if (res.httpStatus === 200) {
      //   res.data.forEach(item => {
      //     let begin = item.todo.indexOf('【');
      //     let end = item.todo.indexOf('】');
      //     dispatch(
      //       creator('plan/updateType', {
      //         _id: item._id,
      //         data: { type: item.todo.slice(begin + 1, end) },
      //       }),
      //     );
      //   });
      // }
    });
    dispatch(creator('hobby/query', id));
  }

  //键盘事件
  onKeyDown = e => {
    if (e.keyCode === 13) {
      this.add();
    }
  };

  //增加
  add = () => {
    const { dispatch, form } = this.props;
    const id = window.sessionStorage.getItem(userId);
    form.validateFields((err, fields) => {
      if (!err) {
        fields.id = id;
        fields.date = moment();
        fields.type = this.state.value;
        let sDate = moment('0000-01-01');
        let eDate = moment('9999-12-31');
        dispatch(creator('plan/addToDoList', fields)).then(res => {
          if (res.httpStatus === 200) {
            dispatch(creator('plan/getToDoList', { id, sDate, eDate }));
            //清空输入框
            form.resetFields();
          }
        });
      }
    });
  };
  //完成
  handleOperate = (status, record) => {
    const { dispatch } = this.props;
    const id = window.sessionStorage.getItem(userId);
    let sDate = moment('0000-01-01');
    let eDate = moment('9999-12-31');
    record.id = id;
    record.status = status;
    record.time = this.state.time;
    record.complexity = this.state.complexity;
    dispatch(creator('plan/operate', record)).then(res => {
      if (res.httpStatus === 200) {
        dispatch(creator('plan/getToDoList', { id, sDate, eDate }));
      } else {
      }
    });
  };

  //所选行变化时
  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys, selectedRows });
  };

  //成就弹出框
  toggleAchievement = () => {
    this.setState(
      {
        achievementModal: !this.state.achievementModal,
      },
      () => {
        if (this.state.achievementModal) {
          const { dispatch } = this.props;
          const id = window.sessionStorage.getItem(userId);
          let sDate = moment('0000-01-01');
          let eDate = moment('9999-12-31');
          dispatch(creator('plan/getAchievementList', { id, sDate, eDate, type: 'all' }));
        }
      },
    );
  };
  //当天未处理事项标红
  setRowClassName = (record, index) => {
    let itemDate = moment(record.date).format(dateFormat);
    let today = moment().format(dateFormat);
    let flag = moment(itemDate).isSame(today);

    return flag ? '' : styles.red;
    // return styles.red
  };
  handleChange = value => {
    this.setState({ value });
  };
  selectBefore = () => {
    const { hobbies } = this.props.hobby;
    return (
      <Select style={{ width: 90 }} value={this.state.value} onChange={this.handleChange}>
        {hobbies.map(item => (
          <Option value={item.hobby}>{item.hobby}</Option>
        ))}
      </Select>
    );
  };
  toggle = () => {
    this.setState({ visible: !this.state.visible });
  };
  openDescModal = record => {
    this.setState({ record, time: 0, complexity: 0 });
    this.toggle();
  };
  complete = () => {
    this.handleOperate('completed', this.state.record);
    this.toggle();
  };
  render() {
    const { loading, toDoList, totalValue, totalCoin } = this.props.plan;

    const { getFieldDecorator } = this.props.form;
    const rowSelection = {
      selectedRows: this.state.selectedRows,
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const columns = [
      {
        title: '事项',
        dataIndex: 'todo',
        width: '30%',
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: '30%',
        render: text => {
          if (text === 'active') {
            return (
              <div
                title="进行中"
                style={{ width: 12, height: 12, background: 'rgb(255,165,0)', borderRadius: '50%' }}
              ></div>
            );
          } else if (text === 'completed') {
            return (
              <div
                title="完成"
                style={{ width: 12, height: 12, background: 'rgb(69,199,0)', borderRadius: '50%' }}
              ></div>
            );
          } else {
            return (
              <div
                title="放弃"
                style={{ width: 12, height: 12, background: 'rgb(236,0,0)', borderRadius: '50%' }}
              ></div>
            );
          }
        },
      },
      {
        title: '完成',
      },
      {
        title: '操作',
        render: (text, record) => (
          <span>
            <Button
              style={{ borderRadius: 10 }}
              size="small"
              // onClick={this.handleOperate.bind(this, 'completed', record)}
              onClick={this.openDescModal.bind(this, record)}
              disabled={record.status == 'active' ? false : true}
            >
              <Icon type="check" />
            </Button>

            <Button
              style={{ marginLeft: 10, borderRadius: 10 }}
              size="small"
              onClick={this.handleOperate.bind(this, 'abandon', record)}
              disabled={record.status == 'active' ? false : true}
            >
              <Icon type="close" />
            </Button>
          </span>
        ),
      },
    ];

    return (
      <Global>
        <div>
          <Form style={{ display: 'flex', justifyContent: 'space-between' }}>
            <Form.Item>
              {getFieldDecorator('todo', {
                rules: [
                  {
                    required: true,
                    message: '请输入待办事项',
                  },
                ],
              })(
                <Input
                  style={{ width: 750, marginRight: 5 }}
                  placeholder="请输入待办事项"
                  onKeyDown={this.onKeyDown}
                  addonBefore={this.selectBefore()}
                />,
                // <Search
                //   placeholder="input search text"
                //   enterButton="Search"
                //   size="large"
                //   onKeyDown={this.onKeyDown}
                //   onSearch={this.add.bind(this)}
                // />,
              )}
            </Form.Item>
            <Form.Item>
              <Button type="primary" onClick={this.add.bind(this)}>
                增加
              </Button>
            </Form.Item>
          </Form>
        </div>
        {toDoList.length ? (
          <main>
            <Table
              rowSelection={rowSelection}
              columns={columns}
              dataSource={toDoList}
              pagination={
                toDoList.length > 10
                  ? {
                      total: toDoList.length,
                      showTotal: total => `共${total}条数据`,
                      showSizeChanger: true,
                      size: 'small',
                      pageSizeOptions: ['10', '100', '1000'],
                    }
                  : false
              }
              rowKey="_id"
              loading={loading}
              rowClassName={this.setRowClassName}
            />
          </main>
        ) : (
          <img src={beachSrc} style={{ marginLeft: 200 }} />
        )}
        <div style={{ padding: 20 }}>
          <a onClick={this.toggleAchievement}>
            <IconFont type="icon-tongji" style={{ fontSize: 20 }} /> 成就值
            <b className={`${styles.red} ${styles.achievement}`}>{totalValue}</b>
          </a>
          <a onClick={this.toggleAchievement}>
            <IconFont type="icon-xiaochengxu_tubiao-" style={{ fontSize: 20, marginLeft: 10 }} />{' '}
            成就币<b className={`${styles.red} ${styles.achievement}`}>{totalCoin}</b>
          </a>
        </div>

        {/* 成就弹出框 */}
        <Achievement
          visible={this.state.achievementModal}
          toggleAchievement={this.toggleAchievement}
        />

        <Modal
          title={
            <>
              <Icon type="check-circle" theme="twoTone" twoToneColor="#52c41a" />
              <span style={{ marginLeft: 4 }}>任务完成描述</span>
            </>
          }
          visible={this.state.visible}
          onOk={this.complete}
          onCancel={this.toggle}
        >
          任务耗时：
          <Slider value={this.state.time} onChange={time => this.setState({ time })} />
          任务复杂度：
          <Slider
            value={this.state.complexity}
            onChange={complexity => this.setState({ complexity })}
          />
        </Modal>
      </Global>
    );
  }
}

// export default Plan;

const WrappedPlan = Form.create({ name: 'plan' })(Plan);

export default connect(({ plan, hobby, loading }) => ({
  plan,
  hobby,
  loading: loading.models.plan,
}))(WrappedPlan);
